<?php
/*
Plugin Name: Vril's Transparent PNG Fix
Plugin URI: http://vril.vn.ua/vrils-Transparent-PNG-fix-WordPress-plugin.html
Description: Adds support for the transparent PNG images available both to good browsers and Internet Explorer.
Author: Alex Kot
Version: 1.3
Author URI: http://vril.vn.ua/
*/ 


define('ATTRIB_REGEXP', '/%s\s*=\s*(\'[^\']*\'|"[^"]*"|[^\s]+)/i');


function get_attrib_value($tag_str , $attrib_name ,  $part_and_complete_pair = false , $strip_quotes = true )
{
	$matches = null;
	$result  = false;
	if( preg_match( sprintf( ATTRIB_REGEXP , preg_quote($attrib_name) ) , $tag_str, $matches) )
	{
		
		if($strip_quotes)
		{
			$first_char = $matches[1]{0};
			$last_char  = $matches[1]{strlen($matches[1]) - 1};
			if( 
			    ( $first_char == '"' ) && ( $last_char == '"' ) ||
			    ( $first_char == "'" ) && ( $last_char == "'" ) 
			  )
			{
				$result =  substr( $matches[1] , 1, -1);
			}
		}
		else 
		{
			$result =  $matches[1];
		}
		
		if($part_and_complete_pair)
		{
			$result = array($matches[0] , $result);
		}
	}
	return $result;	
}


function replace_style($tag_str , $style_arr , $new_style_str)
{	
	$result_str = $tag_str;
	if($style_arr !== false)
	{
		return str_replace($style_arr[0] , $new_style_str , $tag_str );
	}
	else 
	{
		return preg_replace('/^(\S+\s)/i' , '$1 ' . $new_style_str . ' ' , $result_str);
	}
}

function replace_png_images($matches)
{
	$src       = null;
	$height    = null;
	$width     = null;
	
	$tag_str =  $matches[0];
	
	if(($src = get_attrib_value($tag_str , 'src')) === false)
	{
		return $tag_str;
	}
	
	if( !(strtolower ( substr($src , -4)) == '.png'))
	{
		return $tag_str;
	}
	
	if(($height = get_attrib_value($tag_str , 'height')) === false)
	{
		return $tag_str;	
	}
	
	if(($width = get_attrib_value($tag_str , 'width')) === false)
	{
		return $tag_str;	
	}
	
	$style = get_attrib_value($tag_str, 'style' , true);
	

	
	return "<div style='border:0px; width:${width}px; height:${height}px; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\"$src\");'>" . 		      
		      replace_style($tag_str , $style , "style='border:0; width:${width}px; display:block; margin:0px; padding:0px; height:${height}px; filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);'" ).
	       "</div>";

	
	
	
}

function fix_png($content)
{
	return preg_replace_callback('|<img([^><]+)class\s*\=\s*[\'"]?transparent\-png[\'"]?([^><]+)>|i', 'replace_png_images' , $content);
}

add_filter('the_content', 'fix_png');

?>